// main.js - Loads and interacts with the WebAssembly module

// We'll dynamically import the wasm module once it's built
let wasmModule = null;
let isLoading = true;

// Elements
const emailInput = document.getElementById('email');
const timestampInput = document.getElementById('timestamp');
const signatureTextarea = document.getElementById('signature');
const decryptBtn = document.getElementById('decrypt-btn');
const outputDiv = document.getElementById('output');

// Display loading state initially
outputDiv.innerHTML = '<span class="loading">Loading WebAssembly module...</span>';

// This function will be called once the page is loaded
async function init() {
  try {
    // Import the WASM module from the pkg directory generated by wasm-pack
    try {
      // Try to load the actual WASM module first
      const { default: initWasm, decrypt_reward_data } = await import('./pkg/wasm_aes.js');
      await initWasm();
      
      wasmModule = { decrypt_reward_data };
      console.log("WASM module loaded successfully");
    } catch (wasmError) {
      // If WASM loading fails, fall back to a mock implementation
      // This allows the UI to function even before the WASM is built
      console.warn("Failed to load WASM module, using mock implementation:", wasmError);
      
      wasmModule = {
        decrypt_reward_data: (email, timestamp, encrypted_str) => {
          // This is just a simulation of what the WASM module would do
          console.log("Mock decryption (WASM not loaded) called with:", { email, timestamp, encrypted_str });
          // Just return the input for demonstration
          return atob(encrypted_str);
        }
      };
      
      // Add warning to the output
      outputDiv.innerHTML = '<span style="color: orange">⚠️ Using mock decryption (WASM not built yet)</span>';
    }
    
    isLoading = false;
    outputDiv.innerHTML = '<span>Ready to decrypt data</span>';
    decryptBtn.disabled = false;
    
    // Add event listener for decrypt button
    decryptBtn.addEventListener('click', decryptData);
    
    console.log("WASM module initialized successfully");
  } catch (error) {
    console.error("Failed to initialize WASM module:", error);
    outputDiv.innerHTML = `<span style="color: red">Error loading WASM module: ${error.message}</span>`;
  }
}

// Function to decrypt the reward data
async function decryptData() {
  if (isLoading) {
    alert("Please wait for the WASM module to load");
    return;
  }
  
  try {
    const email = emailInput.value.trim();
    const timestamp = timestampInput.value.trim();
    const signature = signatureTextarea.value.trim();
    
    // Validate inputs
    if (!email) {
      alert("Email is required");
      return;
    }
    if (!timestamp) {
      alert("Timestamp is required");
      return;
    }
    if (!signature) {
      alert("Encrypted signature is required");
      return;
    }
    
    // Call the WASM decryption function
    let decrypted;
    try {
      console.log("Decrypting data with:", { email, timestamp, signature });
      decrypted = wasmModule.decrypt_reward_data(email, timestamp, signature);
      // 兼容 wasm 返回 Promise 或直接返回
      if (decrypted instanceof Promise) {
        decrypted = await decrypted;
      }
    } catch (e) {
      outputDiv.innerHTML = `<span style="color: red">Decryption error: ${e.message || e}</span>`;
      return;
    }
    
    outputDiv.innerHTML = `<pre>${decrypted}</pre>`;
    console.log("Decrypted output:", decrypted);
  } catch (error) {
    console.error("Decryption error:", error);
    outputDiv.innerHTML = `<span style="color: red">Decryption error: ${error.message}</span>`;
  }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', init);

// Note: In a real application, after running `wasm-pack build --target web`,
// you would import the actual WASM module from the pkg directory